package com.yang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.mapper.AdminMapper;
import com.yang.pojo.Admin;
import com.yang.pojo.LoginAdmin;
import com.yang.service.AdminService;
import com.yang.util.JwtUtil;
import com.yang.util.RedisCache;
import com.yang.util.ResponseResult;
import org.hamcrest.core.IsNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 朝阳
 * @since 2021-11-26
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService, UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public UserDetails loadUserByUsername(String adminname) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getAdminname,adminname);
        Admin admin = adminMapper.selectOne(queryWrapper);
        //如果没有查询到用户就抛出异常
        if (Objects.isNull(admin)){
            throw new RuntimeException("用户名或密码错误");
        }
        //TODO 查询对应的权限信息
//        List<String> permissionKeyList =  adminMapper.selectOne(user.getId());
//        List<String> list = new ArrayList<>(Arrays.asList("admin","user"));
        //把数据封装成UserDetails返回
        return new LoginAdmin(admin, Collections.singletonList(admin.getPermissions()));
    }

    @Override
    public ResponseResult login(Admin admin) {
        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(admin.getAdminname(),admin.getAdminpassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        LoginAdmin loginAdmin = (LoginAdmin) authenticate.getPrincipal();
        String adminid = loginAdmin.getAdmin().getAdminid().toString();
        String jwt = JwtUtil.createJWT(adminid);
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        //把完整的用户信息存入redis userid作为key
        redisCache.setCacheObject("login:" + adminid,loginAdmin);
        return new ResponseResult(200,"登陆成功",map);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginAdmin loginAdmin = (LoginAdmin) authentication.getPrincipal();
        Integer adminid = loginAdmin.getAdmin().getAdminid();
        //删除redis中的值
        redisCache.deleteObject("login:"+adminid);
        return new ResponseResult(200,"注销成功");
    }
}
